package com.longxi.tianjintianbao.ui.presenter.repair;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.util.Log;

import com.longxi.tianjintianbao.AppConst;
import com.longxi.tianjintianbao.MyApplication;
import com.longxi.tianjintianbao.R;
import com.longxi.tianjintianbao.api.ApiRetrofit;
import com.longxi.tianjintianbao.api.response.BaseResponse;
import com.longxi.tianjintianbao.exception.ExceptionHandle;
import com.longxi.tianjintianbao.exception.MySubscriber;
import com.longxi.tianjintianbao.model.RepairDetail;
import com.longxi.tianjintianbao.ui.activity.repair_publish.RepairActivity;
import com.longxi.tianjintianbao.ui.adapter.FullyGridLayoutManager;
import com.longxi.tianjintianbao.ui.adapter.GridImageAdapter;
import com.longxi.tianjintianbao.ui.base.BaseActivity;
import com.longxi.tianjintianbao.ui.base.BasePresenter;
import com.longxi.tianjintianbao.ui.view.repair.IUpdateRepairContentAtView;
import com.longxi.tianjintianbao.utils.LogUtils;
import com.longxi.tianjintianbao.utils.MyUtils;
import com.longxi.tianjintianbao.widget.iosdialog.ActionSheetDialog;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.luck.picture.lib.config.PictureMimeType.ofImage;

public class UpdateRepairContentAtPresenter extends BasePresenter<IUpdateRepairContentAtView> {

    public static String REPAIRDETAIL = "REPAIRDETAIL";//序列化数据
    public static String REPAIRAREA = "REPAIRAREA";//客户区域0 公共区域1
    public static String REGIONID = "REGIONID";//小区id
    public static String REGIONNAME = "REGIONNAME";//忘记了

    public String CUSTTYPE_YG = "1";// 1-员工
    public String CUSTTYPE_ZH = "0";// 0-租户
    public String custtype = CUSTTYPE_YG;

    String regionname = "";
    String regiontype = "";
    String repairarea ="";
    String buildId = "";
    private RepairDetail repairDetail;

    public UpdateRepairContentAtPresenter(BaseActivity context) {
        super(context);
    }

    public void setBar() {
        Intent intent = mContext.getIntent();
        repairDetail = (RepairDetail) intent.getSerializableExtra(REPAIRDETAIL);
        getView().getEtAddress().setEnabled(false);
        getView().getEtAddress().setEnabled(false);
        getView().getEtAddress().setFocusableInTouchMode(false);
        mContext.setTitle("修改报修单");
        mContext.setTvLeft(MyUtils.getString(R.string.back));

        getView().getTvRepairArea().setText("维修区域: " + repairDetail.getRegion() + "\n维修类型: " + repairDetail.getRepairtype() + "\n维修类别: " + repairDetail.getRepaircategory());
        getView().getTvSelectArea().setText(repairDetail.getBuildname());
        getView().getEtAddress().setText(repairDetail.getAddress());
        getView().getEtContent().setText(repairDetail.getContent());
        getView().getTvRequireDate().setText(repairDetail.getArrangedate());
        if(!"".equals(repairDetail.getImage1())){
            selectList.add(new LocalMedia(repairDetail.getImage1(), 0, 0, ""));
        }
        if(!"".equals(repairDetail.getImage2())){
            selectList.add(new LocalMedia(repairDetail.getImage2(), 0, 0, ""));
        }

        custtype = repairDetail.getCusttype();
        if("1".equals(custtype)){
            getView().getRgCustomType().check(R.id.rBtnYG);
        }else{
            getView().getRgCustomType().check(R.id.rBtnZH);
        }

    }

    public void onActivityResult(int requestCode, Intent data) {
        switch (requestCode) {
            case PictureConfig.CHOOSE_REQUEST:
                // 图片选择结果回调
                selectList = PictureSelector.obtainMultipleResult(data);
                // 例如 LocalMedia 里面返回三种path
                // 1.media.getPath(); 为原图path
                // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
                for (LocalMedia media : selectList) {
                    LogUtils.i("图片-----》", media.getPath());
                }
                adapter.setList(selectList);
                adapter.notifyDataSetChanged();
                break;
            case AppConst.IntentRequstCode.ACTIVITY_REPAIR_CONTENT:
                if(data != null){
                    buildId = data.getStringExtra("buildId");
                    getView().getTvSelectArea().setText(data.getStringExtra("area"));
                    getView().getEtAddress().setText(data.getStringExtra("address"));
                }
                break;
            case AppConst.IntentRequstCode.ACTIVITY_REPAIR:
                repairDetail.setRepairtype(data.getStringExtra(AppConst.REPAIRTYPE));
                repairDetail.setRepaircategory(data.getStringExtra(AppConst.REPAIRCATEGORY));
                if("0".equals(data.getStringExtra(AppConst.REGION))){
                    repairDetail.setRegion("客户区域");
                }else{
                    repairDetail.setRegion("公共区域");
                }

                StringBuffer stringBuffer = new StringBuffer();
                stringBuffer.append("维修区域: " + repairDetail.getRegion());
                stringBuffer.append("\n维修类型: " + repairDetail.getRepairtype());
                stringBuffer.append("\n维修类别: " + repairDetail.getRepaircategory());
//                stringBuffer.append("\n客户类型: " + ("1".equals(repairDetail.getCusttype()) ? "员工" : "租户"));
                getView().getTvRepairArea().setText(stringBuffer);
                break;
        }
    }

    public void updateEventRepair() {
        long userid = MyApplication.loginUser.userid;
        String region = "";
        String addressid = repairDetail.getAddressid();
        String address = getView().getEtAddress().getText().toString().trim();
        String content = getView().getEtContent().getText().toString().trim();

        if("".equals(content) || content == null){
            MyUtils.showToast("请输入维修内容");
            return;
        }

        if(!"".equals(dateTime)){
            repairDetail.setArrangedate(dateTime);
        }

        mContext.showWaitingDialog(MyUtils.getString(R.string.load));
        JSONObject object = new JSONObject();
        try {
            object.put("billid", repairDetail.getBillid());
            object.put("userid", userid);
            if("客户区域".equals(repairDetail.getRegion())){
                region = "0";
            }else if("公共区域".equals(repairDetail.getRegion())){
                region = "1";
            }
            object.put("region", region);
            object.put("repairtype", repairDetail.getRepairtype());
            object.put("repaircategory", repairDetail.getRepaircategory());
            object.put("addressid", repairDetail.getAddressid());
            object.put("address", repairDetail.getAddress());
            object.put("contacts", repairDetail.getContacts());
            object.put("contactsid", repairDetail.getAddressid());
            object.put("contactsphone", repairDetail.getContactsphone());
            object.put("content", content);

            String image1 = "";
            String image2 = "";
            for (int i = 0; i < selectList.size(); i++) {
                if(selectList.get(i).getCompressPath() == null || "".equals(selectList.get(i).getCompressPath())){
                    if(i == 0){
                        image1 = selectList.get(i).getPath();
                    }else if(i == 1){
                        image2 = selectList.get(i).getPath();
                    }
                }else{
                    if(i == 0){
                        image1 = MyUtils.imageToBase64(selectList.get(i).getCompressPath());
                    }else if(i == 1){
                        image2 = MyUtils.imageToBase64(selectList.get(i).getCompressPath());
                    }
                }
            }

            object.put("image1", image1);
            object.put("image2", image2);
            object.put("imagereplace", listToString(imagereplace, "，"));
            object.put("arrangedate", repairDetail.getArrangedate());
            object.put("assetscode", repairDetail.getAssetscode());
            object.put("assetsname", repairDetail.getAssetsname());
            object.put("custtype", custtype);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ApiRetrofit.getInstance().saveEventRepair(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<BaseResponse>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                mContext.hideWaitingDialog();
                if(baseResponse.getCode() != 0){
                    MyUtils.showToast(baseResponse.getMsg());
                    return;
                }
                MyUtils.showToast("修改成功");
                Intent intent = new Intent();
                intent.putExtra("content", content);
                mContext.setResult(Activity.RESULT_OK, intent);
                mContext.finish();
            }
        });
    }

    public void initPicture() {
        FullyGridLayoutManager manager = new FullyGridLayoutManager(mContext, 3, GridLayoutManager.VERTICAL, false);
        getView().getRecyclerView().setLayoutManager(manager);
        adapter = new GridImageAdapter(mContext, onAddPicClickListener);
        adapter.setList(selectList);
        adapter.setSelectMax(2);
        getView().getRecyclerView().setAdapter(adapter);
    }

    private List<LocalMedia> selectList = new ArrayList<>();
    private GridImageAdapter adapter;
    private List<String> imagereplace = new ArrayList<>();
    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {
            boolean mode = true;
            if (mode) {
                // 进入相册 以下是例子：不需要的api可以不写
                PictureSelector.create(mContext)
                .openGallery(ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .theme(R.style.picture_default_style)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
                .maxSelectNum(2)// 最大图片选择数量
                .minSelectNum(1)// 最小选择数量
                .imageSpanCount(4)// 每行显示个数
                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选
                .previewImage(true)// 是否可预览图片
                .isCamera(true)// 是否显示拍照按钮
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                //.imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                //.setOutputCameraPath("/CustomPath")// 自定义拍照保存路径
                .enableCrop(false)// 是否裁剪
                .compress(true)// 是否压缩
                .synOrAsy(true)//同步true或异步false 压缩 默认同步
                //.compressSavePath(getPath())//压缩图片保存地址
                //.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .withAspectRatio(16, 9)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                .hideBottomControls(false)// 是否显示uCrop工具栏，默认不显示
                .isGif(false)// 是否显示gif图片
                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                .circleDimmedLayer(false)// 是否圆形裁剪
                .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
                .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
                .openClickSound(false)// 是否开启点击声音
                .selectionMedia(selectList)// 是否传入已选图片
                //.isDragFrame(false)// 是否可拖动裁剪框(固定)
//                        .videoMaxSecond(15)
//                        .videoMinSecond(10)
                //.previewEggs(false)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
                //.cropCompressQuality(90)// 裁剪压缩质量 默认100
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                //.cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效
                //.rotateEnabled(true) // 裁剪是否可旋转图片
                //.scaleEnabled(true)// 裁剪是否可放大缩小图片
                //.videoQuality()// 视频录制质量 0 or 1
                //.videoSecond()//显示多少秒以内的视频or音频也可适用
                //.recordVideoSecond()//录制视频秒数 默认60s
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
            }
        }

        @Override
        public void onDeletePic(LocalMedia localMedia) {
            if(localMedia.getCompressPath() == null || "".equals(localMedia.getCompressPath())){
                imagereplace.add(localMedia.getPath());
            }
        }

        @Override
        public void onPreview(int position) {
            PictureSelector.create(mContext).themeStyle(R.style.picture_default_style).openExternalPreview(position, selectList);
        }
    };

    public String listToString(List<String> list, String fgf) {
        if(list.size() == 0){
            return "";
        }
        String sb = "";
        for (String url : list) {
            sb += fgf + url;
        }
        return sb.substring(1);
    }

    /**
     * 弹出底部多选item
     */
    public void showSelectRepairArea() {
        new ActionSheetDialog(mContext)
        .builder()
        .setTitle("请选择报修区域")
        .addSheetItem("客户区域", ActionSheetDialog.SheetItemColor.Orange,
        new ActionSheetDialog.OnSheetItemClickListener() {
            @Override
            public void onClick(int which) {
                Intent mainIntent = new Intent(mContext, RepairActivity.class);
                mainIntent.putExtra(AppConst.REPAIRAREA,"indoorArea.json");
                mainIntent.putExtra(AppConst.REGION,"0");
                mainIntent.putExtra(AppConst.STATE,true);
                mContext.startActivityForResult(mainIntent, AppConst.IntentRequstCode.ACTIVITY_REPAIR);
            }
        })
        .addSheetItem("公共区域", ActionSheetDialog.SheetItemColor.Orange,
        new ActionSheetDialog.OnSheetItemClickListener() {
            @Override
            public void onClick(int which) {
                Intent mainIntent = new Intent(mContext, RepairActivity.class);
                mainIntent.putExtra(AppConst.REPAIRAREA,"outdoorArea.json");
                mainIntent.putExtra(AppConst.REGION,"1");
                mainIntent.putExtra(AppConst.STATE,true);
                mContext.startActivityForResult(mainIntent, AppConst.IntentRequstCode.ACTIVITY_REPAIR);
            }
        }).show();
    }
}
